package learn.spring.auth.config;

import learn.spring.auth.entity.AuthUser;
import learn.spring.auth.feign.FeignService;
import learn.spring.common.JsonUtils;
import learn.spring.common.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class LoginUserDetailsService implements UserDetailsService {

    @Autowired
    private FeignService feignService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        查出userId
        String user = JsonUtils.toJson(feignService.getUserIdByName(username).getData().get("user"));
        log.error("===================== user {}", user);
        UserDto userDto = JsonUtils.fromJson(user, UserDto.class);
        log.error("===================== userDto {}", userDto);
//        根据userId 查找对应的角色
        List<String> roleIds = (List<String>) feignService.getRoleIdsByUserId(userDto.getUserId())
                .getData().get("roleIds");
        log.error("===================== roleIds {}", roleIds);
//        查找所有的角色名
        List<String> roles = (List<String>) feignService.getRolesByIds(roleIds).getData().get("roles");
        log.error("===================== roles {}", roles);

        AuthUser authUser = new AuthUser();
        authUser.setUsername(username);
//        todo
        authUser.setPassword(userDto.getPassword());
        authUser.setAuthorities(roles.stream()
                .map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        log.error("===================== authUser {}", authUser);
        return authUser;
    }
}
